﻿using System;
using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Interop;
using GalaSoft.MvvmLight.Messaging;

namespace Songhay.Silverlight.BiggestBox
{
    using Songhay.Composition;
    using Songhay.Mvvm.Models;
    using Songhay.Silverlight.BiggestBox.Models;
    using Songhay.Mvvm;

    [Export(typeof(ICompositionMessaging))]
    public class CompositionMessaging : ICompositionMessaging
    {
        #region ICompositionMessaging Members

        public void RegisterMessageReceivers()
        {
            //TODO this MVVM Light Message registration is not used?
            Messenger.Default.Register<LightNotificationMessageAction<SilverlightHost>>(this,
            message =>
            {
                if(message.Notification != "BiggestBox") return;

                message.Execute(BiggestBoxCompositionHost.MefHost.NavigationHost);
            });

            Messenger.Default.Register<NotificationMessageAction<AboutViewMessage>>(this,
                message =>
                {
                    var parameter = new AboutViewMessage
                    {
                        AboutAssemblyReference = this.GetType().Assembly
                    };
                    message.Execute(parameter);
                });
        }

        public void SendCompositionMessages()
        {
            this.SendClientViewMessage();
            this.SendClientSettingsMessage();
        }

        #endregion

        void ReceiveClientNavigationMessages(INavigationFrame view)
        {
            Messenger.Default.Register<LightNavigationMessage<string>>(view,
                message =>
                {
                    if(view.IsNavigating || (message == null)) return;

                    if(message.Content == "#togglefullembed")
                    {
                        var currentUri = HtmlPage.Document.DocumentUri;
                        var mode = "/Mode/FullEmbed"; //TODO make this configurable
                        var location = currentUri.GetComponents(
                            UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.SafeUnescaped);

                        if(currentUri.OriginalString.Contains(mode))
                            HtmlPage.Window.Navigate(new Uri(location.Replace(mode, "/")), "_self");
                        else
                            HtmlPage.Window.Navigate(new Uri(location.TrimEnd('/') + mode), "_self");
                    }
                    else if(message.HasWellFormedUriString && message.TargetUri.IsAbsoluteUri)
                        HtmlPage.Window.Navigate(message.TargetUri, "_self");
                    else
                        HtmlPage.Window.Navigate(new Uri("#" + message.TargetLocation, UriKind.Relative), "_self");
                });
        }

        void SendClientViewMessage()
        {
            var message = new LightNotificationMessageAction<INavigationFrame>("ClientView",
            data =>
            {
                BiggestBoxCompositionHost.MefHost.NavigationTarget = data.NavigationFrame;

                //Register Navigation Messaging for entire Composition:
                this.ReceiveClientNavigationMessages(data);
            })
            {
                Source = LightMessageSource.CompositionMessagingCore
            };

            Messenger.Default.Send(message);
        }

        void SendClientSettingsMessage()
        {
            var key = Application.Current.Host.InitParams["config"];
            var dictionary = HtmlPageUtility.GetClientSettings(key);

            var properties = new ClientSettings
            {
                OpmlIndex = new Uri(dictionary["UriOpmlIndex"], UriKind.Relative),
                JsonHeader = new Uri(dictionary["UriJsonHeader"], UriKind.Relative)
            };

            var message = new GenericMessage<ClientSettings>(properties);
            Messenger.Default.Send(message);
        }
    }
}
